package com.gframework.biz.datasource.init;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import com.gframework.boot.flyway.IFlywayHookSPI;

/**
 * 将T_SYS_PARAMETER表配置的参数添加到当前环境配置中.
 * 
 * @since 2.0.0
 * @author Ghwolf
 */
public class DataBaseParamInit implements IFlywayHookSPI{
	private static final Logger logger = LoggerFactory.getLogger(DataBaseParamInit.class);
	/**
	 * 配置项来源名称
	 */
	private static final String PROPERTY_SOURCE_NAME = "{database:t_sys_parameter}";
	
	/**
	 * 查询参数的sql
	 */
	private static final String SEARCH_SQL = "SELECT * FROM t_sys_parameter WHERE deleted=0";
	
	@Override
	public void afterMigrate(FlywayProperties pro, ConfigurableEnvironment env) {
		
		if (Boolean.FALSE.equals(env.getProperty("gframework.flyway.init-db-sys-parameter",Boolean.class))) {
			return ;
		}
		if (Boolean.FALSE.equals(env.getProperty("gframework.flyway.init-gframework-basic-table",Boolean.class))) {
			return ;
		}
		
		Map<String,Object> map = new HashMap<>();
		
		try (Connection conn = DriverManager.getConnection(pro.getUrl(),pro.getUser(),pro.getPassword());
				Statement st = conn.createStatement();){
			st.execute(SEARCH_SQL);
			ResultSet rs = st.getResultSet();
			try {
				while(rs.next()) {
					String key = rs.getString("PARAM_KEY");
					String value = rs.getString("PARAM_VALUE");
					String defaultValue = rs.getString("DEFAULT_VALUE");
					String saveValue = value == null ? defaultValue : value;
					map.put(key, saveValue == null ? "" : saveValue);
					if (logger.isInfoEnabled()) {
						logger.info("从数据库添加了一个新的配置项：[{}]=[{}]",key,saveValue);
					}
				}
			} finally {
				rs.close();
			}
		} catch (SQLException e) {
			logger.error("从数据库读取参数信息异常！\nurl:{}\nuser:{}",pro.getUrl(),pro.getUser(),e);
		}
		
		if (!map.isEmpty()) {
			Map<String,Object> paramMap = new ConcurrentHashMap<>(map);
			PropertySource<Map<String,Object>> source = new MapPropertySource(PROPERTY_SOURCE_NAME,paramMap);
			env.getPropertySources().addLast(source);
		}
		
	}

}
